package com.zimin.cloud.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zimin.cloud.mine.pojo.system.business.AccountBO;
import com.zimin.cloud.mine.pojo.system.view.AccountRoleVO;
import com.zimin.cloud.system.pojo.entity.AccountPost;
import com.zimin.cloud.system.pojo.entity.AccountRole;
import com.zimin.cloud.system.mapper.AccountRoleMapper;
import com.zimin.cloud.system.pojo.entity.Role;
import com.zimin.cloud.system.service.IAccountRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zimin.cloud.system.service.IRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户角色关联表 服务实现类
 * </p>
 *
 * @author zimin
 * @since 2021-12-30 11:05
 */
@Service("accountRoleService")
@Slf4j
public class AccountRoleServiceImpl extends ServiceImpl<AccountRoleMapper, AccountRole> implements IAccountRoleService {

    @Autowired
    private IRoleService roleService;

    @Override
    public boolean removeByRoleIds(Collection<? extends Serializable> idList) {
        return remove(Wrappers.<AccountRole>lambdaQuery().in(AccountRole::getRoleId, idList));
    }

    @Override
    public boolean save(AccountBO accountBO) {
        var accountRole = AccountRole.builder()
                .accountId(accountBO.getId())
                .roleId(accountBO.getRoleId())
                .build();
        return save(accountRole);
    }

    @Override
    public boolean update(AccountBO accountBO) {
        return update(Wrappers.<AccountRole>lambdaUpdate().set(AccountRole::getRoleId,
                accountBO.getRoleId()).eq(AccountRole::getAccountId, accountBO.getId()));
    }

    @Override
    public List<String> getRolePermissions(String accountId) {
        return roleService.listByIds(listByAccountId(accountId).parallelStream().map(AccountRole::getRoleId).collect(Collectors.toList()))
                .parallelStream().map(Role::getRoleKey).collect(Collectors.toList());
    }

    @Override
    public List<AccountRole> listByAccountId(String accountId) {
        return list(Wrappers.<AccountRole>lambdaQuery().eq(AccountRole::getAccountId, accountId));
    }
}
